package demo.model;

import java.util.ArrayList;
import java.util.List;

import javax.xml.bind.JAXBElement;

import generated.BIBLEBOOK;
import generated.XMLBIBLE;

@SuppressWarnings("restriction")
public class Bible {
	final XMLBIBLE xmlBible;
	public String biblename;
	public String title;
	public String creator;
	public String contributors;
	public String description;
	public String publisher;
	public String id;
	public String language;
	public String eula;
	public String source;
	public List<Book> books = new ArrayList<Book>();
	
	public static Bible createFromZefania(final String filename, final XMLBIBLE xmlBible){
		return new Bible(filename, xmlBible);
	}

	private Bible(final String id, final XMLBIBLE xmlBible) {
		this.xmlBible = xmlBible;
		this.biblename = this.xmlBible.getBiblename();

		// Read bible metadata
		this.readMetaData();
		if (this.id == null) {
			this.id = id;
		}
		
		this.id = this.id.toLowerCase();

		// Read bible books
		for(BIBLEBOOK bibleBook : this.xmlBible.getBIBLEBOOK()){
			this.books.add(Book.createFromZefania(bibleBook));
		}
	}

	private void readMetaData() {
		// Setup title, creator and description
		List<JAXBElement<?>> elements = this.xmlBible.getINFORMATION()
				.getTitleOrCreatorOrDescription();
		for (JAXBElement element : elements) {
			String elementName = element.getName().getLocalPart();
			Object oValue = element.getValue();
			String value = "";
			if(oValue instanceof String)
				value =(String) oValue;
			if ("title".equals(elementName)) {
				this.title = value;
			} else if ("creator".equals(elementName)) {
				this.creator = value;
			} else if ("description".equals(elementName)) {
				this.description = value;
			} else if ("publisher".equals(elementName)) {
				this.publisher = value;
			} else if ("contributors".equals(elementName)) {
				this.contributors = value;
			} else if ("identifier".equals(elementName)) {
				this.id = value;
			} else if ("language".equals(elementName)) {
				this.language = value;
			} else if ("rights".equals(elementName)) {
				this.eula = value;
			} else if ("source".equals(elementName)) {
				this.source = value;
			}

		}
	}
}
